package com.zzy.system.service.impl;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzy.common.core.redis.RedisCache;
import com.zzy.common.utils.StringUtils;
import com.zzy.common.utils.guanmai.GuanmaiCommon;
import com.zzy.system.domain.*;
import com.zzy.system.domain.vo.PurchaseOrderVO;
import com.zzy.system.mapper.*;
import com.zzy.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import javax.imageio.*;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PushDataServiceImpl implements IPushDataService {

    private static final Logger log = LoggerFactory.getLogger(PushDataServiceImpl.class);

    // 注入 RedisCache 对象
    @Autowired
    private OutStockSheetOrderMapper outStockSheetOrderMapper;
    @Autowired
    private OutStockSheetOrderDetailMapper outStockSheetOrderDetailMapper;

    @Autowired
    private DetectReportPicturesMapper detectReportPicturesMapper;

    @Autowired
    private PurchaseInStockOrderMapper purchaseInStockOrderMapper;
    @Autowired
    private GuanmaiSupplierMapper guanmaiSupplierMapper;

    @Autowired
    private PurchaseInStockOrderDetailItemMapper purchaseInStockOrderDetailItemMapper;
    @Autowired
    private GuanmaiCustomerMapper guanmaiCustomerMapper;

    @Autowired
    private GuanmaiSpuMapper guanmaiSpuMapper;

    @Autowired
    private GuanmaiCustomerItemMapper guanmaiCustomerItemMapper;
    @Autowired
    private ISaleOrderPushLogService iSaleOrderPushLogService;
    @Autowired
    private PurchaseOrderDetailMapper purchaseOrderDetailMapper;
    @Autowired
    private PurchaseInStockOrderDetailMapper purchaseInStockOrderDetailMapper;
    @Autowired
    private SysDicCityMapper sysDicCityMapper;
    @Autowired
    private OutStockSheetOrderDetailBatchMapper outStockSheetOrderDetailBatchMapper;
    @Autowired
    private AreaCodeMapper areaCodeMapper;
    @Autowired
    private PurchaseRefundOrderMapper purchaseRefundOrderMapper;
    @Autowired
    private PurchaseRefundOrderDetailMapper purchaseRefundOrderDetailMapper;

    /**
     * 从溯源平台获取供应商信息
     *
     * @param guanmaiSupplier
     * @return
     * @throws Exception
     */
    @Override
    public GuanmaiSupplier getChongqingSupplier(GuanmaiSupplier guanmaiSupplier) throws Exception {
        if (guanmaiSupplier != null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("deptName", guanmaiSupplier.getSupplierName());
            //1采购商 2供应商
            jsonObject.put("deptType", 2);
            jsonObject.put("current", 1);
            jsonObject.put("size", 10);
            jsonObject.put("ownerSocialCreditCode", "91500000327800333Q");
            jsonObject.put("ownerLicenseNumber", "JY15001120077343");
            String result = GuanmaiCommon.pushChongqing("/api/subjectInfo/page", jsonObject.toJSONString());
            System.out.println(result);
            try {
                JSONObject resultJson = JSON.parseObject(result);
                int code = resultJson.getIntValue("code");
                if (code == 200) {
                    JSONObject dataObject = resultJson.getJSONObject("data");
                    JSONArray recordsArray = dataObject.getJSONArray("records");
                    if (!recordsArray.isEmpty()) {
                        JSONObject recordObject = recordsArray.getJSONObject(0);
                        // 获取 uuid 字段的值
                        System.out.println("deptId: " + recordObject.getString("deptId"));
                        UpdateWrapper<GuanmaiSupplier> guanmaiSupplierUpdateWrapper = new UpdateWrapper<>();
                        guanmaiSupplier.setDeptId(recordObject.getString("deptId"));
                        guanmaiSupplierUpdateWrapper.eq("supplier_id", guanmaiSupplier.getSupplierId())
                                .set("dept_id", recordObject.getString("deptId"))
                                .set("is_push", 1)
                                .set("push_date", new Date());
                        guanmaiSupplierMapper.update(null, guanmaiSupplierUpdateWrapper);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return guanmaiSupplier;
    }

    @Override
    public GuanmaiSupplier getCustomerFromChongqing() throws Exception {
        QueryWrapper<GuanmaiCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_push", 1);
        queryWrapper.isNull("dept_id");
        List<GuanmaiCustomer> list = guanmaiCustomerMapper.selectList(queryWrapper);
        for (GuanmaiCustomer guanmaiCustomer : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("deptName", guanmaiCustomer.getCustomerName());
            //1采购商 2供应商
            jsonObject.put("deptType", 1);
            jsonObject.put("current", 1);
            jsonObject.put("size", 10);
            jsonObject.put("ownerSocialCreditCode", "91500000327800333Q");
            jsonObject.put("ownerLicenseNumber", "JY15001120077343");
            String result = GuanmaiCommon.pushChongqing("/api/subjectInfo/page", jsonObject.toJSONString());
            System.out.println(result);
            try {
                JSONObject resultJson = JSON.parseObject(result);
                int code = resultJson.getIntValue("code");
                if (code == 200) {
                    JSONObject dataObject = resultJson.getJSONObject("data");
                    JSONArray recordsArray = dataObject.getJSONArray("records");
                    if (!recordsArray.isEmpty()) {
                        JSONObject recordObject = recordsArray.getJSONObject(0);
                        // 获取 uuid 字段的值
                        System.out.println("deptId: " + recordObject.getString("deptId"));
                        System.out.println("pkid: " + recordObject.getString("pkid"));
                        UpdateWrapper<GuanmaiCustomer> guanmaiSupplierUpdateWrapper = new UpdateWrapper<>();
                        guanmaiCustomer.setDeptId(recordObject.getString("deptId"));
                        guanmaiCustomer.setPkid(recordObject.getString("pkid"));
                        guanmaiSupplierUpdateWrapper.eq("customer_id", guanmaiCustomer.getCustomerId())
                                .set("dept_id", recordObject.getString("deptId"))
                                .set("pkid", recordObject.getString("pkid"));
                        guanmaiCustomerMapper.update(null, guanmaiSupplierUpdateWrapper);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    /**
     * 推送商户到陕生鲜
     *
     * @return
     * @throws Exception
     */
    @Override
    public String pushCustomerToShanshengxian() throws Exception {
        return "";
    }

    @Override
    public String pushStationToShanshengxian() throws Exception {
        //规格型号
        return "";
    }

    /**
     * 新增供应商到溯源平台
     *
     * @param guanmaiSupplier
     * @throws Exception
     */
    @Override
    public String pushSupplier(GuanmaiSupplier guanmaiSupplier) throws Exception {
//        guanmaiSupplier.setSupplierName("重庆市新锡涵食品有限公司（糕点）");
//        guanmaiSupplier.setBusinessLicence("91500116MABNQ21NXY");
//        guanmaiSupplier.setAreaCode("500103");
        JSONObject jsonObject = new JSONObject();
        JSONObject data = new JSONObject();
        jsonObject.put("deptName", guanmaiSupplier.getSupplierName());
        jsonObject.put("deptAddress", guanmaiSupplier.getCompanyAddress());
        //1生产 3经营 4餐饮
        jsonObject.put("deptCategory", 1);
        jsonObject.put("areaCode", guanmaiSupplier.getAreaCode());
        jsonObject.put("sortOrder", 1);
        //税号
        jsonObject.put("socialCreditCode", guanmaiSupplier.getBusinessLicence());
        //许可证
        jsonObject.put("licenseNumber", guanmaiSupplier.getBusinessLicence());
        //营业执照图片
        //jsonObject.put("businessLicenseImage", guanmaiSupplier.getBusinessLicence());
        data.put("ownerSocialCreditCode", "91500000327800333Q");
        data.put("ownerLicenseNumber", "JY15001120077343");
        data.put("sysDeptInfo", jsonObject);
        String result = GuanmaiCommon.pushChongqing("/api/subjectInfo/addSupplier", data.toJSONString());
        System.out.println(result);
        return "";
    }

    /**
     * 新增供应商到溯源平台
     *
     * @param guanmaiCustomer
     * @throws Exception
     */
    @Override
    public String pushCustomer(GuanmaiCustomer guanmaiCustomer) throws Exception {
        QueryWrapper<GuanmaiCustomer> guanmaiCustomerQueryWrapper = new QueryWrapper<>();
        guanmaiCustomerQueryWrapper.eq("is_push", 0);
        List<GuanmaiCustomer> guanmaiCustomerList = guanmaiCustomerMapper.selectList(guanmaiCustomerQueryWrapper);

        QueryWrapper<AreaCode> areaCodeQueryWrapper = new QueryWrapper<>();
        areaCodeQueryWrapper.eq("level", "3");
        List<AreaCode> areaCodeList = areaCodeMapper.selectList(areaCodeQueryWrapper);


        QueryWrapper<SysDicCity> sysDicCityQueryWrapper = new QueryWrapper<>();
        sysDicCityQueryWrapper.eq("level", "40");
        List<SysDicCity> sysDicCityList = sysDicCityMapper.selectList(sysDicCityQueryWrapper);
        for (GuanmaiCustomer guanmaiCustomer1 : guanmaiCustomerList) {
            QueryWrapper<GuanmaiCustomerItem> guanmaiCustomerItemQueryWrapper = new QueryWrapper<>();
            guanmaiCustomerItemQueryWrapper.eq("customer_id", guanmaiCustomer1.getCustomerId());
            List<GuanmaiCustomerItem> guanmaiCustomerItemList = guanmaiCustomerItemMapper.selectList(guanmaiCustomerItemQueryWrapper);
            if (guanmaiCustomerItemList.isEmpty()) {
                continue;
            }
            SysDicCity sysDicCity = FilterSysDicCityBySupplier(sysDicCityList, guanmaiCustomer1.getAreaLevel1Name());
            JSONObject jsonObject = new JSONObject();
            JSONObject data = new JSONObject();
            jsonObject.put("deptName", guanmaiCustomer1.getCustomerName());
            jsonObject.put("deptAddress", guanmaiCustomer1.getCustomerAddress());
            //1生产 3经营 4餐饮
            jsonObject.put("deptCategory", 2);
            if (sysDicCity != null) {
                jsonObject.put("areaCode", sysDicCity.getDicAreaCode());
            } else {
                //匹配重庆市外的区县地址
                AreaCode areaCode = FilterAreaCodeBySupplier(areaCodeList, guanmaiCustomer1.getAreaLevel1Name());
                if (areaCode != null) {
                    jsonObject.put("areaCode", areaCode.getCode());
                } else {
                    continue;
                }
            }

            jsonObject.put("sortOrder", 1);
            //税号
            if (guanmaiCustomerItemList.get(0).getTaxNum() == null || guanmaiCustomerItemList.get(0).getTaxNum().equals("")) {
                continue;
            }
            jsonObject.put("socialCreditCode", guanmaiCustomerItemList.get(0).getTaxNum());
            //许可证
            jsonObject.put("licenseNumber", guanmaiCustomerItemList.get(0).getTaxNum());
            //营业执照图片
            //jsonObject.put("businessLicenseImage", guanmaiCustomerItemList.get(0).getb);
            data.put("ownerSocialCreditCode", "91500000327800333Q");
            data.put("ownerLicenseNumber", "JY15001120077343");
            data.put("sysDeptInfo", jsonObject);
            String result = GuanmaiCommon.pushChongqing("/api/subjectInfo/addPurchase", data.toJSONString());
            System.out.println(result);
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode jsonNode = objectMapper.readTree(result);
                int code = jsonNode.get("code").asInt();
                if (code == 201 || code == 200) {
                    UpdateWrapper<GuanmaiCustomer> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("customer_id", guanmaiCustomer1.getCustomerId()).set("is_push", 1).set("push_date", new Date());
                    guanmaiCustomerMapper.update(null, updateWrapper);
                }
                System.out.println("code 的值是: " + code);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return "";
    }

    /**
     * 推送商品到溯源平台
     *
     * @param guanmaiSpu1
     * @return
     * @throws Exception
     */
    @Override
    public String pushSpu(GuanmaiSpu guanmaiSpu1) throws Exception {
        QueryWrapper<GuanmaiSpu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_push", 0);
        List<GuanmaiSpu> guanmaiSpus = guanmaiSpuMapper.selectList(queryWrapper);
        for (GuanmaiSpu guanmaiSpu : guanmaiSpus) {
            JSONObject data = new JSONObject();
            //商品类别
            data.put("productCategorySub", guanmaiSpu.getRemarks2());
            data.put("productName", guanmaiSpu.getSpuName());
            //1采购商 2供应商
            String[] image = guanmaiSpu.getImagePath().split(",");
            if (image != null && image.length > 0) {
                data.put("pic", image[0]);
            } else {
                return "";
            }
            data.put("productCategory", guanmaiSpu.getRemarks1());
            //税号
            data.put("productAlias", guanmaiSpu.getSpuName());
            data.put("ownerSocialCreditCode", "91500000327800333Q");
            data.put("ownerLicenseNumber", "JY15001120077343");
            String result = GuanmaiCommon.pushChongqing("/api/productInformation/save", data.toJSONString());
            System.out.println(result);
            if (result != null && !"".equals(result)) {
                JSONObject jsonObject = JSON.parseObject(result);
                int code = jsonObject.getIntValue("code");
                if (code == 200) {
                    // 获取 data 字段的值
                    String prodId = jsonObject.getString("data");
                    UpdateWrapper<GuanmaiSpu> guanmaiSpuUpdateWrapper = new UpdateWrapper<>();
                    guanmaiSpuUpdateWrapper.eq("spu_id", guanmaiSpu.getSpuId()).set("prod_id", prodId)
                            .set("is_push", 1).set("push_date", new Date());
                    guanmaiSpuMapper.update(null, guanmaiSpuUpdateWrapper);
                }

            }
        }

        return "";
    }

    @Override
    public String getCustomerFromShanshengxian(String xydm, String customerId) throws Exception {
        return "shanshengxianId";
    }

    @Override
    public String getSupplierFromShanshengxian(String xydm, String supplierId) throws Exception {
        return "";
    }

    public static GuanmaiSupplier filterFirstBysupplierId(List<GuanmaiSupplier> guanmaiSupplierList, String supplierId) {
        // 检查列表是否为空或 supplierId 是否为 null
        if (guanmaiSupplierList == null || guanmaiSupplierList.isEmpty() || supplierId == null) {
            return null;
        }
        // 使用 Stream API 进行筛选操作
        Optional<GuanmaiSupplier> firstMatch = guanmaiSupplierList.stream()
                // 通过 supplierId 进行条件匹配
                .filter(guanmaiSupplier -> supplierId.equals(guanmaiSupplier.getSupplierId()))
                // 查找第一个匹配的元素
                .findFirst();
        // 如果存在匹配的元素，返回该元素，否则返回 null
        return firstMatch.orElse(null);
    }

    public static GuanmaiSpu filterSpuById(List<GuanmaiSpu> guanmaiSpuList, String spuId) {
        // 检查列表是否为空或 supplierId 是否为 null
        if (guanmaiSpuList == null || guanmaiSpuList.isEmpty() || spuId == null) {
            return null;
        }
        // 使用 Stream API 进行筛选操作
        Optional<GuanmaiSpu> firstMatch = guanmaiSpuList.stream()
                // 通过 supplierId 进行条件匹配
                .filter(guanmaiSpu -> spuId.equals(guanmaiSpu.getSpuId()))
                // 查找第一个匹配的元素
                .findFirst();
        // 如果存在匹配的元素，返回该元素，否则返回 null
        return firstMatch.orElse(null);
    }

    public static SysDicCity FilterSysDicCityBySupplier(List<SysDicCity> sysDicCityList, String supplierArea) {
        // 检查列表是否为空或 supplierId 是否为 null
        if (sysDicCityList == null || sysDicCityList.isEmpty() || supplierArea == null) {
            return null;
        }
        // 使用 Stream API 进行筛选操作
        Optional<SysDicCity> firstMatch = sysDicCityList.stream()
                // 通过 supplierId 进行条件匹配
                .filter(sysDicCity -> supplierArea.equals(sysDicCity.getShortName()) || supplierArea.equals(sysDicCity.getFullShortName()))
                // 查找第一个匹配的元素
                .findFirst();
        // 如果存在匹配的元素，返回该元素，否则返回 null
        return firstMatch.orElse(null);
    }

    public static AreaCode FilterAreaCodeBySupplier(List<AreaCode> areaCodeList, String area) {
        // 检查列表是否为空或 supplierId 是否为 null
        if (areaCodeList == null || areaCodeList.isEmpty() || area == null) {
            return null;
        }
        // 使用 Stream API 进行筛选操作
        Optional<AreaCode> firstMatch = areaCodeList.stream()
                // 通过 supplierId 进行条件匹配
                .filter(areaCode -> area.equals(areaCode.getName()))
                // 查找第一个匹配的元素
                .findFirst();
        // 如果存在匹配的元素，返回该元素，否则返回 null
        return firstMatch.orElse(null);
    }

    public static SysDicCity FilterSysDicCityByAreaCode(List<SysDicCity> sysDicCityList, String areaCode) {
        // 检查列表是否为空或 supplierId 是否为 null
        if (sysDicCityList == null || sysDicCityList.isEmpty() || areaCode == null) {
            return null;
        }
        // 使用 Stream API 进行筛选操作
        Optional<SysDicCity> firstMatch = sysDicCityList.stream()
                // 通过 supplierId 进行条件匹配
                .filter(sysDicCity -> areaCode.equals(sysDicCity.getDicAreaCode()))
                // 查找第一个匹配的元素
                .findFirst();
        // 如果存在匹配的元素，返回该元素，否则返回 null
        return firstMatch.orElse(null);
    }

    //采购入库推送
    @Override
    public String pushInStockOrder() throws Exception {
        //查询供应商
        QueryWrapper<GuanmaiSupplier> guanmaiSupplierQueryWrapper = new QueryWrapper<>();
        guanmaiSupplierQueryWrapper.ge("guanmai_supplier_id", 0);
        List<GuanmaiSupplier> guanmaiSupplierList = guanmaiSupplierMapper.selectList(guanmaiSupplierQueryWrapper);
        //查询采购入库待推送的T61599站点的审核通过的入库单数据
        QueryWrapper<PurchaseInStockOrderDetail> purchaseInStockOrderDetailQueryWrapper = new QueryWrapper<>();
        purchaseInStockOrderDetailQueryWrapper.eq("is_push", 0);
        purchaseInStockOrderDetailQueryWrapper.eq("station_id", "T61599");
        //查询所有已经推送的商品id
        QueryWrapper<GuanmaiSpu> guanmaiSpuQueryWrapper = new QueryWrapper<>();
        guanmaiSpuQueryWrapper.eq("is_push", 1);
        guanmaiSpuQueryWrapper.isNotNull("prod_id");
        List<GuanmaiSpu> guanmaiSpuList = guanmaiSpuMapper.selectList(guanmaiSpuQueryWrapper);
        //查询重庆市内的区县
        QueryWrapper<SysDicCity> sysDicCityQueryWrapper = new QueryWrapper<>();
        sysDicCityQueryWrapper.eq("level", 40);
        List<SysDicCity> sysDicCityList = sysDicCityMapper.selectList(sysDicCityQueryWrapper);
        List<PurchaseInStockOrderDetail> purchaseInStockOrderDetailList = purchaseInStockOrderDetailMapper.selectList(purchaseInStockOrderDetailQueryWrapper);
        for (PurchaseInStockOrderDetail purchaseInStockOrderDetail : purchaseInStockOrderDetailList) {
            GuanmaiSupplier guanmaiSupplier = filterFirstBysupplierId(guanmaiSupplierList, purchaseInStockOrderDetail.getSupplierId());
            if (guanmaiSupplier == null) {
                continue;
            }

            //查询采购入库子项
            QueryWrapper<PurchaseInStockOrderDetailItem> purchaseInStockOrderDetailItemQueryWrapper = new QueryWrapper<>();
            purchaseInStockOrderDetailItemQueryWrapper.eq("in_stock_sheet_id", purchaseInStockOrderDetail.getInStockSheetId());
            purchaseInStockOrderDetailItemQueryWrapper.le("push_error_num", 11);
            List<PurchaseInStockOrderDetailItem> purchaseInStockOrderDetailItemList = purchaseInStockOrderDetailItemMapper.selectList(purchaseInStockOrderDetailItemQueryWrapper);
            for (PurchaseInStockOrderDetailItem purchaseInStockOrderDetailItem : purchaseInStockOrderDetailItemList) {
                GuanmaiSpu guanmaiSpu = filterSpuById(guanmaiSpuList, purchaseInStockOrderDetailItem.getSpuId());

                if (guanmaiSpu == null) {
                    return "";
                }
                //如果商品大类是预包装 进行预包装入库
                if (guanmaiSpu.getRemarks1().equals("1")) {
                    pushPreInStockOrder(purchaseInStockOrderDetailItem, guanmaiSpu, sysDicCityList, guanmaiSupplier, purchaseInStockOrderDetail.getInStockDate());
                } else if (guanmaiSpu.getRemarks1().equals("2")) {
                    pushAgricultureInStockOrder(purchaseInStockOrderDetailItem, guanmaiSpu, sysDicCityList, guanmaiSupplier, purchaseInStockOrderDetail.getInStockDate());
                } else {
                    continue;
                }

            }
        }
        return "";
    }

    /**
     * 预包装商品入库
     *
     * @return
     * @throws Exception
     */
    public String pushPreInStockOrder(PurchaseInStockOrderDetailItem purchaseInStockOrderDetailItem, GuanmaiSpu guanmaiSpu, List<SysDicCity> sysDicCityList, GuanmaiSupplier guanmaiSupplier, String inStockDate) throws Exception {
        JSONObject jsonObject = new JSONObject();

        jsonObject.put("productId", guanmaiSpu.getProdId());
        //如果供应商不在重庆市内区县中 那么属于经营入库
        SysDicCity sysDicCity = FilterSysDicCityByAreaCode(sysDicCityList, guanmaiSupplier.getAreaCode());
        if (sysDicCity == null) {
            //经营入库
            jsonObject.put("sourceType", 2);
            jsonObject.put("socialCreditCode", guanmaiSupplier.getBusinessLicence());
            jsonObject.put("licenseNumber", guanmaiSupplier.getBusinessLicence());
        } else {
            //生产入库
            jsonObject.put("sourceType", 1);
        }
        //重报生鲜 信用代码
        jsonObject.put("ownerSocialCreditCode", "91500000327800333Q");
        //重报生鲜 营业执照
        jsonObject.put("ownerLicenseNumber", "JY15001120077343");
        JSONArray jsonArray = new JSONArray();
        JSONObject spuJson = new JSONObject();
        spuJson.put("productQuantity", purchaseInStockOrderDetailItem.getInStockCount());
        spuJson.put("productSource", 1);
        spuJson.put("productCode", "1234567891234");
        if(purchaseInStockOrderDetailItem.getShelfLifeDays()!=null){
            spuJson.put("shelfLife", purchaseInStockOrderDetailItem.getShelfLifeDays());
        }else{
            spuJson.put("shelfLife", 90);
        }
        spuJson.put("shelfLifeUnit", 3);
        spuJson.put("productionBatchNo", purchaseInStockOrderDetailItem.getBatchNumber());
        spuJson.put("productionDate", inStockDate);
        spuJson.put("specificationUnit", 2);
        spuJson.put("specification", 1);
        List<DetectReportPictures> detectReportPictures = new ArrayList<>();
        if (purchaseInStockOrderDetailItem.getBatchNumber() != null && !purchaseInStockOrderDetailItem.getBatchNumber().equals("")) {
            detectReportPictures = detectReportPicturesMapper.getPicturesBatchs(purchaseInStockOrderDetailItem.getBatchNumber());
        }
        if (detectReportPictures.isEmpty()) {
            detectReportPictures = detectReportPicturesMapper.getPictures(purchaseInStockOrderDetailItem.getSpuId());
        }
        String filePath = detectReportPictures.stream()
                .map(DetectReportPictures::getPicture)
                .collect(Collectors.joining(","));
        spuJson.put("qualificationCertificate", filePath);
        JSONArray boxArray = new JSONArray();
        JSONObject boxJson = new JSONObject();
        boxJson.put("boxCode", purchaseInStockOrderDetailItem.getBatchNumber());
        boxArray.add(boxJson);
        // spuJson.put("boxList",boxArray);
        jsonArray.add(spuJson);
        jsonObject.put("prePackagedProductBatchInfoSaveDtoList", jsonArray);
        System.out.println(jsonObject);
        String result = GuanmaiCommon.pushChongqing("/api/warehouse/prePackagedExternalStorage", jsonObject.toJSONString());
        System.out.println(result);
        savePushLog(purchaseInStockOrderDetailItem.getBatchNumber(), "预产品入库", jsonObject.toJSONString(), result);
        try {
            // 解析 JSON 字符串为 JSONObject
            JSONObject resultJson = JSONObject.parseObject(result);
            // 判断 code 是否为 200
            if (resultJson.getIntValue("code") == 200) {
                // 获取 data 数组
                JSONArray dataArray = resultJson.getJSONArray("data");
                // 获取 data 数组中的第一个元素
                String sourceCode = dataArray.getString(0);
                UpdateWrapper<PurchaseInStockOrderDetailItem> purchaseInStockOrderDetailItemUpdateWrapper = new UpdateWrapper<>();
                purchaseInStockOrderDetailItemUpdateWrapper.eq("purchase_in_stock_order_detail_item_id", purchaseInStockOrderDetailItem.getPurchaseInStockOrderDetailItemId())
                        .set("is_push", 1).set("push_date", new Date()).set("source_code", sourceCode);
                purchaseInStockOrderDetailItemMapper.update(null, purchaseInStockOrderDetailItemUpdateWrapper);
                System.out.println(sourceCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 农产品入库
     *
     * @return
     * @throws Exception
     */
    public String pushAgricultureInStockOrder(PurchaseInStockOrderDetailItem purchaseInStockOrderDetailItem, GuanmaiSpu guanmaiSpu, List<SysDicCity> sysDicCityList, GuanmaiSupplier guanmaiSupplier, String inStockDate) throws Exception {
        JSONObject jsonObject = new JSONObject();

        jsonObject.put("productId", guanmaiSpu.getProdId());
        //如果供应商不在重庆市内区县中 那么属于经营入库
        SysDicCity sysDicCity = FilterSysDicCityByAreaCode(sysDicCityList, guanmaiSupplier.getAreaCode());
        if (sysDicCity == null) {
            //经营入库
            jsonObject.put("sourceType", 2);
            jsonObject.put("socialCreditCode", guanmaiSupplier.getBusinessLicence());
            jsonObject.put("licenseNumber", guanmaiSupplier.getBusinessLicence());
        } else {
            //生产入库
            jsonObject.put("sourceType", 1);
        }
        //重报生鲜 信用代码
        jsonObject.put("ownerSocialCreditCode", "91500000327800333Q");
        //重报生鲜 营业执照
        jsonObject.put("ownerLicenseNumber", "JY15001120077343");
        JSONArray jsonArray = new JSONArray();
        JSONObject spuJson = new JSONObject();
        spuJson.put("productQuantity", purchaseInStockOrderDetailItem.getInStockCount());
        spuJson.put("productSource", 1);
        spuJson.put("productCode", "1234567891234");
        if(purchaseInStockOrderDetailItem.getShelfLifeDays()!=null){
            spuJson.put("shelfLife", purchaseInStockOrderDetailItem.getShelfLifeDays());
        }else{
            spuJson.put("shelfLife", 180);
        }
        spuJson.put("shelfLifeUnit", 3);
        spuJson.put("productionBatchNo", purchaseInStockOrderDetailItem.getBatchNumber());
//        if(purchaseInStockOrderDetailItem.getProductionTime()!=null){
//            spuJson.put("productionDate", purchaseInStockOrderDetailItem.getProductionTime());
//        }else{
            spuJson.put("productionDate", inStockDate);
//        }

        spuJson.put("specificationUnit", 2);
        spuJson.put("specification", 1);
        spuJson.put("productionDateType", 2);
        List<DetectReportPictures> detectReportPictures = new ArrayList<>();
        if (purchaseInStockOrderDetailItem.getBatchNumber() != null && !purchaseInStockOrderDetailItem.getBatchNumber().equals("")) {
            detectReportPictures = detectReportPicturesMapper.getPicturesBatchs(purchaseInStockOrderDetailItem.getBatchNumber());
        }
        if (detectReportPictures.isEmpty()) {
            detectReportPictures = detectReportPicturesMapper.getPictures(purchaseInStockOrderDetailItem.getSpuId());
        }
        String filePath = detectReportPictures.stream()
                .map(DetectReportPictures::getPicture)
                .collect(Collectors.joining(","));
        spuJson.put("qualificationCertificate", filePath);
        spuJson.put("qualificationCertificateType", 1);
//        JSONArray boxArray = new JSONArray();
//        JSONObject boxJson = new JSONObject();
//        boxJson.put("boxCode", purchaseInStockOrderDetailItem.getBatchNumber());
//        boxArray.add(boxJson);
        // spuJson.put("boxList",boxArray);
        jsonArray.add(spuJson);
        jsonObject.put("agricultureProductBatchInfoSaveDtoList", jsonArray);
        System.out.println(jsonObject);
        String result = GuanmaiCommon.pushChongqing("/api/warehouse/agricultureStorageExternal", jsonObject.toJSONString());
        System.out.println(result);
        savePushLog(purchaseInStockOrderDetailItem.getBatchNumber(), "农产品入库", jsonObject.toJSONString(), result);
        try {
            // 解析 JSON 字符串为 JSONObject
            JSONObject resultJson = JSONObject.parseObject(result);
            // 判断 code 是否为 200
            if (resultJson.getIntValue("code") == 200) {
                // 获取 data 数组
                JSONArray dataArray = resultJson.getJSONArray("data");
                // 获取 data 数组中的第一个元素
                String sourceCode = dataArray.getString(0);
                UpdateWrapper<PurchaseInStockOrderDetailItem> purchaseInStockOrderDetailItemUpdateWrapper = new UpdateWrapper<>();
                purchaseInStockOrderDetailItemUpdateWrapper.eq("purchase_in_stock_order_detail_item_id", purchaseInStockOrderDetailItem.getPurchaseInStockOrderDetailItemId())
                        .set("is_push", 1).set("push_date", new Date()).set("source_code", sourceCode);
                purchaseInStockOrderDetailItemMapper.update(null, purchaseInStockOrderDetailItemUpdateWrapper);
                System.out.println(sourceCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static PurchaseInStockOrderDetailItem FilterInstockByBatchNum(List<PurchaseInStockOrderDetailItem> purchaseInStockOrderDetailItemList, String batchNum) {
        // 检查列表是否为空或 supplierId 是否为 null
        if (batchNum == null || batchNum.isEmpty() || batchNum == null) {
            return null;
        }
        // 使用 Stream API 进行筛选操作
        Optional<PurchaseInStockOrderDetailItem> firstMatch = purchaseInStockOrderDetailItemList.stream()
                // 通过 supplierId 进行条件匹配
                .filter(purchaseInStockOrderDetailItem -> batchNum.equals(purchaseInStockOrderDetailItem.getBatchNumber()))
                // 查找第一个匹配的元素
                .findFirst();
        // 如果存在匹配的元素，返回该元素，否则返回 null
        return firstMatch.orElse(null);
    }

    public static GuanmaiCustomerItem filterCustomerById(List<GuanmaiCustomerItem> guanmaiCustomerList, String customerId) {
        // 检查列表是否为空或 customerId 是否为 null
        if (customerId == null || customerId.isEmpty() || customerId == null) {
            return null;
        }
        // 使用 Stream API 进行筛选操作
        Optional<GuanmaiCustomerItem> firstMatch = guanmaiCustomerList.stream()
                // 通过 supplierId 进行条件匹配
                .filter(guanmaiCustomer -> customerId.equals(guanmaiCustomer.getCustomerId()))
                // 查找第一个匹配的元素
                .findFirst();
        // 如果存在匹配的元素，返回该元素，否则返回 null
        return firstMatch.orElse(null);
    }

    @Override
    public String pushSaleOrder() throws Exception {
        QueryWrapper<OutStockSheetOrder> outStockSheetOrderQueryWrapper = new QueryWrapper<>();
        outStockSheetOrderQueryWrapper.eq("is_push", 0);
        List<OutStockSheetOrder> outStockSheetOrderList = outStockSheetOrderMapper.selectList(outStockSheetOrderQueryWrapper);

        QueryWrapper<GuanmaiCustomerItem> guanmaiCustomerItemQueryWrapper = new QueryWrapper<>();
        guanmaiCustomerItemQueryWrapper.ge("guanmai_customer_item_id", 0);
        List<GuanmaiCustomerItem> guanmaiCustomerItemList = guanmaiCustomerItemMapper.selectList(guanmaiCustomerItemQueryWrapper);
        //查询出已经推送过得入库数据 需要用到箱码
        QueryWrapper<PurchaseInStockOrderDetailItem> purchaseInStockOrderDetailItemQueryWrapper = new QueryWrapper<>();
        purchaseInStockOrderDetailItemQueryWrapper.eq("is_push", 1);
        purchaseInStockOrderDetailItemQueryWrapper.isNotNull("source_code");
        List<PurchaseInStockOrderDetailItem> purchaseInStockOrderDetailItemList = purchaseInStockOrderDetailItemMapper.selectList(purchaseInStockOrderDetailItemQueryWrapper);
        for (OutStockSheetOrder outStockSheetOrder : outStockSheetOrderList) {
            QueryWrapper<OutStockSheetOrderDetail> outStockSheetOrderDetailQueryWrapper = new QueryWrapper<>();
            outStockSheetOrderDetailQueryWrapper.eq("is_push", 0);
            outStockSheetOrderDetailQueryWrapper.eq("out_stock_sheet_id", outStockSheetOrder.getOutStockSheetId());
            JSONObject jsonObject = new JSONObject();
            GuanmaiCustomerItem guanmaiCustomer = filterCustomerById(guanmaiCustomerItemList, outStockSheetOrder.getCustomerId());
            if (guanmaiCustomer == null || guanmaiCustomer.getTaxNum() == null) {
                continue;
            }
            jsonObject.put("purchaseSocialCreditCode", guanmaiCustomer.getTaxNum());
            jsonObject.put("purchaseLicenseNumber", guanmaiCustomer.getTaxNum());
            jsonObject.put("ownerSocialCreditCode", "91500000327800333Q");
            jsonObject.put("ownerLicenseNumber", "JY15001120077343");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            LocalDateTime dateTime = LocalDateTime.parse(outStockSheetOrder.getOutStockDate(), formatter);
            String dateStr = dateTime.toLocalDate().toString();
            jsonObject.put("shipmentTime", dateStr);
            jsonObject.put("orderType", 2);
            JSONArray jsonArray = new JSONArray();
            List<OutStockSheetOrderDetail> outStockSheetOrderDetailList = outStockSheetOrderDetailMapper.selectList(outStockSheetOrderDetailQueryWrapper);
            for (OutStockSheetOrderDetail outStockSheetOrderDetail : outStockSheetOrderDetailList) {
                QueryWrapper<OutStockSheetOrderDetailBatch> outStockSheetOrderDetailBatchQueryWrapper = new QueryWrapper<>();
                outStockSheetOrderDetailBatchQueryWrapper.eq("detail_id", outStockSheetOrderDetail.getOutStockSheetOrderDetailId());
                outStockSheetOrderDetailBatchQueryWrapper.eq("out_stock_sheet_id", outStockSheetOrderDetail.getOutStockSheetId());
                List<OutStockSheetOrderDetailBatch> outStockSheetOrderDetailBatchList = outStockSheetOrderDetailBatchMapper.selectList(outStockSheetOrderDetailBatchQueryWrapper);


                for (OutStockSheetOrderDetailBatch orderDetailBatch : outStockSheetOrderDetailBatchList) {
                    //根据出库的批次号查找已经入库的箱码
                    PurchaseInStockOrderDetailItem purchaseInStockOrderDetailItem = FilterInstockByBatchNum(purchaseInStockOrderDetailItemList, orderDetailBatch.getBatchNumber());
                    if (purchaseInStockOrderDetailItem == null) {
                        continue;
                    }
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("sourceCode", purchaseInStockOrderDetailItem.getSourceCode());
                    jsonObject1.put("shipmentQuantity", orderDetailBatch.getStockRatio());
                    jsonArray.add(jsonObject1);
                }
            }
            jsonObject.put("outData", jsonArray);
            if (jsonArray.isEmpty()) {
                continue;
            }
            System.out.println(jsonObject);
            String result = GuanmaiCommon.pushChongqing("/api/orderProductHead/createOrder", jsonObject.toJSONString());
            System.out.println(result);
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode jsonNode = objectMapper.readTree(result);
                int code = jsonNode.get("code").asInt();
                if (code == 200) {
                    String data = jsonNode.get("data").asText();
                    System.out.println("data 的值是: " + data);
                } else {
                    System.out.println("code 不是 200，不获取 data 的值。");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            savePushLog(outStockSheetOrder.getOutOrderId(), "出库发货记录", jsonObject.toJSONString(), result);
        }
        return "";
    }

    @Override
    public String pushPurchaseRefund() throws Exception {
        QueryWrapper<PurchaseRefundOrder> purchaseRefundOrderQueryWrapper = new QueryWrapper<>();
        purchaseRefundOrderQueryWrapper.eq("is_push", 0);
        List<PurchaseRefundOrder> purchaseRefundOrderList = purchaseRefundOrderMapper.selectList(purchaseRefundOrderQueryWrapper);

        QueryWrapper<GuanmaiCustomerItem> guanmaiCustomerItemQueryWrapper = new QueryWrapper<>();
        guanmaiCustomerItemQueryWrapper.ge("guanmai_customer_item_id", 0);
        List<GuanmaiCustomerItem> guanmaiCustomerItemList = guanmaiCustomerItemMapper.selectList(guanmaiCustomerItemQueryWrapper);
        //查询出已经推送过得入库数据 需要用到箱码
        QueryWrapper<PurchaseInStockOrderDetailItem> purchaseInStockOrderDetailItemQueryWrapper = new QueryWrapper<>();
        purchaseInStockOrderDetailItemQueryWrapper.eq("is_push", 1);
        purchaseInStockOrderDetailItemQueryWrapper.isNotNull("source_code");
        List<PurchaseInStockOrderDetailItem> purchaseInStockOrderDetailItemList = purchaseInStockOrderDetailItemMapper.selectList(purchaseInStockOrderDetailItemQueryWrapper);
        for (PurchaseRefundOrder purchaseRefundOrder : purchaseRefundOrderList) {
            QueryWrapper<PurchaseRefundOrderDetails> purchaseRefundOrderDetailsQueryWrapper = new QueryWrapper<>();
            purchaseRefundOrderDetailsQueryWrapper.eq("is_push", 0);
            purchaseRefundOrderDetailsQueryWrapper.eq("supplier_refund_sheet_id", purchaseRefundOrder.getSupplierRefundSheetId());
//
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
//            LocalDateTime dateTime = LocalDateTime.parse(outStockSheetOrder.getOutStockDate(), formatter);
//            String dateStr = dateTime.toLocalDate().toString();
//            jsonObject.put("shipmentTime", dateStr);
//            jsonObject.put("orderType", 2);
//            JSONArray jsonArray = new JSONArray();
            List<PurchaseRefundOrderDetails> purchaseRefundOrderDetailList = purchaseRefundOrderDetailMapper.selectList(purchaseRefundOrderDetailsQueryWrapper);
            for (PurchaseRefundOrderDetails purchaseRefundOrderDetails : purchaseRefundOrderDetailList) {

                JSONObject jsonObject = new JSONObject();

                jsonObject.put("ownerSocialCreditCode", "91500000327800333Q");
                jsonObject.put("ownerLicenseNumber", "JY15001120077343");
                jsonObject.put("cleanReason", "已退回");
                jsonObject.put("cleanReasonType", 2);

                //根据出库的批次号查找已经入库的箱码
                PurchaseInStockOrderDetailItem purchaseInStockOrderDetailItem = FilterInstockByBatchNum(purchaseInStockOrderDetailItemList, purchaseRefundOrderDetails.getBatchNumber());
                if (purchaseInStockOrderDetailItem == null) {
                    continue;
                }
                jsonObject.put("sourceCode", purchaseInStockOrderDetailItem.getSourceCode());
                jsonObject.put("productQuantity", purchaseRefundOrderDetails.getRefundCount());
                System.out.println(jsonObject);
                String result = GuanmaiCommon.pushChongqing("/api/warehouse/storeClean", jsonObject.toJSONString());
                savePushLog(purchaseRefundOrder.getSupplierRefundSheetId(), "清库记录", jsonObject.toJSONString(), result);

                System.out.println(result);
                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    JsonNode jsonNode = objectMapper.readTree(result);
                    int code = jsonNode.get("code").asInt();
                    if (code == 200) {
                        String data = jsonNode.get("data").asText();
                        System.out.println("data 的值是: " + data);
                    } else {
                        System.out.println("code 不是 200，不获取 data 的值。");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }
        return "";
    }

    //记录日志
    public void savePushLog(String pushId, String pushType, String json, String respongse) {
        SaleOrderPushLog saleOrderPushLog = new SaleOrderPushLog();
        saleOrderPushLog.setOrderId(pushId);
        saleOrderPushLog.setType(pushType);
        saleOrderPushLog.setSendContent(json);
        saleOrderPushLog.setResultContent(respongse);
        iSaleOrderPushLogService.saveOrderPushLog(saleOrderPushLog);
    }

    @Override
    public String getToken() throws Exception {
        return "";
    }

    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("LoginName", "123");
        jsonObject.put("Password", "123");
        // 将参数转换为 JSON 字符串
        String jsonStr = jsonObject.toString();
        // 发起 POST 请求
        HttpResponse response = HttpRequest.post("https://192.168.0.31:9005/v1/Login/UserLogin")
                .header("Content-Type", "application/json")
                .body(jsonStr)
                .timeout(20000)
                .execute();
        // 处理响应
        if (response.isOk()) {
            // 请求成功
            String result = response.body();
            System.out.println("请求成功，响应内容：" + result);
        } else {
            // 请求失败
            System.out.println("请求失败，错误信息：" + response.getStatus());
        }
    }

}